<template>
  <div class="search">
    <!-- 1.顶部导航栏 -->
    <van-nav-bar left-arrow title="搜索中心" @click-left="$router.go(-1)">
    </van-nav-bar>
    <!-- 2.搜索框 -->
    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model="value"
      @input="onInput"
    >
      <template #action>
        <div @click="$router.push({ path: '/searchResult', query: { value } })">
          搜索
        </div>
      </template>
    </van-search>
    <!-- 3.推荐词 -->
    <van-cell-group>
      <van-cell
        v-for="(item, index) in showList"
        :key="index"
        icon="search"
        @click="
          $router.push({
            path: '/searchResult',
            query: { keyword: suggestionList[index] },
          })
        "
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 4.搜索历史 -->
    <van-cell-group>
      <van-cell title="历史记录"></van-cell>
      <van-cell
        v-for="item in historyList"
        :key="item"
        :title="item"
        @click="deleteHistory"
      >
        <van-icon name="close"></van-icon>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import {
  getSuggestion,
  deleteSearchHistory,
  getSearchHistory,
} from "./home.js";
export default {
  name: "search",
  data() {
    return {
      value: "", //搜索关键词
      suggestionList: [],
      timeId: null,
      historyList: [],
    };
  },
  methods: {
    onSearch() {
      console.log(this.value);
    },
    onInput() {
      //防抖第一次执行
      clearTimeout(this.timeId);
      // 防抖开启
      this.timeId = setTimeout(async () => {
        if (this.value == "") {
          this.suggestionList = [];
          return;
        }
        // 检查当前关键字是否为空
        if (this.value == "") {
          //非空判断
          this.suggestionList = [];
          return;
          // 调用方法, 发送请求
        }
        const res = await getSuggestion({ q: this.value });
        console.log(res);
        this.suggestionList = res.data.data.options;
      }, 500);
    },
    async deleteHistory(item) {
      let res = await deleteSearchHistory({ message: item });
      console.log(res);
      if (res.status == 204) {
        this.$toast.success("删除成功");
        this.historyList = [];
      } else {
        this.$toast.fail("删除失败");
      }
    },
  },
  async created() {
    let res = await getSearchHistory();
    this.historyList = res.data.data.keywords;
  },
  /* 计算属性 */
  computed: {
    showList() {
      //正则
      let reg = new RegExp(this.value, "gi");
      //数组map映射遍历
      return this.suggestionList.map((value) =>
        value.replace(reg, (match) => `<span style="color:red">${match}</span>`)
      );
    },
  },
};
</script>

<style>
</style>